package com.t2t.top;

import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * Created by yangpengfei on 2016/8/22.
 */
public class PropertiesLoaderUtilsTest2 {
    private static final String SUFFIX_PROPERTIES = ".properties";

    public static void main(String[] args) throws IOException {
        ClassLoader classLoaderToUse = new PropertiesLoaderUtilsTest2().getClass().getClassLoader();

        String resourceName = "MY-META-INF/";

        Enumeration<URL> urls = classLoaderToUse.getResources(resourceName);
        ArrayList<File> files = new ArrayList();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            findFiles(url.getPath(), files);
        }

        List<Properties> properties = findPropertieFiles(files);
        for (Map property : properties) {
            System.out.println(property);
        }
    }

    private static List<Properties> findPropertieFiles(List<File> files) {
        List<Properties> properties = new ArrayList();
        for (File file : files) {
            if (file.getName().endsWith(SUFFIX_PROPERTIES)) {
                try {
                    properties.add(toProperties(new FileInputStream(file)));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return properties;
    }

    public static void findFiles(String path, ArrayList<File> fileName) {
        File file = new File(path);
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                findFiles(f.getAbsolutePath(), fileName);
            } else {
                fileName.add(f);
            }
        }
    }

    public static Properties toProperties(String config) {
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(config.getBytes("UTF-8"));
        } catch (Exception e) {
            System.out.println(e);
        }
        return toProperties(in);
    }

    public static Properties toProperties(InputStream in) {
        Properties properties = new Properties();
        try {
            properties.load(in);
            return properties;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return properties;
    }
}
